package com.fish.yssb.db.excel;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;

import com.fish.yssb.db.bean.BaseInfoTable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;


/**
 * Used 尺寸转换工具类（全）
 */

/**
 * 读取Excel
 */
public class CopyExcel {
    /**Sheet表, Excel表中的底部的表名*/
    private WritableSheet mWritableSheet;
    /**Excel工作簿*/
    private WritableWorkbook mWritableWorkbook;

    private String excelPath="/111/定值备份.xls";;


    public HashMap< String ,BaseInfoTable>  readData(Context context)
    {
        HashMap< String ,BaseInfoTable> list = new HashMap<>();
        InputStream is = null;
        // Excel工作簿
        Workbook workbook = null;

        String filePath = getSDPath()+excelPath;
        File f = new File(filePath);

        try {
            InputStream in = new FileInputStream(f);
            // 获取workbook
            workbook = Workbook.getWorkbook(in);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        Cell cell = null;// 单个单元格

        // 获取sheet, 如果你的workbook里有多个sheet可以利用workbook.getSheets()方法来得到所有的
        Sheet sheet = workbook.getSheet(0);// 这里只取得第一个sheet的值，默认从0开始
        // 开始循环，取得cell里的内容，按具体类型来取

        //遥信
        int sortnum =50000;
        for (int j = 1;j<sheet.getRows();j++){
            BaseInfoTable info = new BaseInfoTable();
            info.setParaType(5);
            info.setChange(false);
            for (int i=0;i<sheet.getColumns();i++){
                // 列,行
                cell = sheet.getCell(i, j);
                if(i==1 && "".equalsIgnoreCase(cell.getContents().trim()))
                {
                    break;
                }

                switch (i)
                {
                    case 0:
                        info.setIdSort(sortnum +j);
                        break;
                    case 1:
                        info.setName(cell.getContents());
                        break;
                    case 2:
                        info.setConnAdr(cell.getContents());
                        break;
                    case 3:
                        info.setUnit(cell.getContents());
                        break;
                    case 4:
                        // 0.无 1.布尔 2.浮点 3.整形 4.字节
                        info.setRealVal(cell.getContents());
                        break;
                }

            }
            if(info.getName()!=null && !"".equalsIgnoreCase(info.getName().trim())) {
                list.put(info.getConnAdr(),info);
            }
        }

        return list;
    }
    public int writeData( ArrayList<BaseInfoTable> dataList )
    {
        int ret = -1;
        try {
            CopyExcel excel = new CopyExcel();
            excel.create();

            excel.addString(0, 0, "序号");
            excel.addString(1, 0, "名称");
            excel.addString(2, 0, "通信地址（16进制）");
            excel.addString(3, 0, "单位");
            excel.addString(4, 0, "数值");

            for(int i=0;i<dataList.size();i++)
            {
                BaseInfoTable info= dataList.get(i);
                excel.addString(0,i+1,  i+1+"");
                excel.addString(1,i+1,  info.getName());
                excel.addString(2,i+1,  info.getConnAdr());
                excel.addString(3,i+1,  info.getUnit());

                excel.addString(4,i+1,info.getRealVal() );
            }
            excel.close();
            ret = 0;
        }catch (Exception ex)
        {

            ex.printStackTrace();
        }
        return ret;

    }


    private boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
//            Toast.makeText(getApplicationContext(), "删除文件失败:" + delFile + "不存在！", Toast.LENGTH_SHORT).show();
            return false;
        } else {

                return deleteSingleFile(delFile);
        }
    }

    private boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
//                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
//                Toast.makeText(getApplicationContext(), "删除单个文件" + filePath$Name + "失败！", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
//            Toast.makeText(getApplicationContext(), "删除单个文件失败：" + filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }



    /**
     * 创建Sheet表s
     * @return Sheet表
     */
    public WritableSheet create(){
        try {
            // 输出Excel的路径
            String filePath = getSDPath()+excelPath;
            delete(filePath);
            // 新建一个文件
            OutputStream os = new FileOutputStream(filePath);
            // 创建Excel工作簿
            mWritableWorkbook = Workbook.createWorkbook(os);
            // 创建Sheet表
            mWritableSheet =  mWritableWorkbook.createSheet("参数定值", 0);
            return  mWritableSheet;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭工作簿
     * @throws IOException
     * @throws WriteException
     */
    public void close() throws IOException, WriteException {
        // 写入数据
        mWritableWorkbook.write();
        // 关闭文件
        mWritableWorkbook.close();
    }

    /**
     * 添加字符串
     * @param col 列号
     * @param row 行号
     * @param text 文本
     * @throws WriteException
     */
    public void addString(int col, int row, String text) throws WriteException {
        if (null == mWritableSheet) return;
        Label label = new Label(col, row, text);
        mWritableSheet.addCell(label);
    }


}